#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import argparse
import sys

def open_camera(camera_id=0):
    """
    根据ID打开相机并显示图像
    
    Args:
        camera_id (int): 相机ID，默认为0（通常是内置摄像头）
    
    Returns:
        None
    """
    # 尝试打开相机
    cap = cv2.VideoCapture(camera_id, cv2.CAP_V4L2)
    cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH,  1280)
    cap.set(cv2.CAP_PROP_FPS, 30)
    
    # 检查相机是否成功打开
    if not cap.isOpened():
        print(f"错误：无法打开相机ID {camera_id}")
        return
    
    print(f"成功打开相机ID {camera_id}")
    
    # 创建两个窗口
    window_name_small = f"相机 {camera_id} (480x640)"
    window_name_large = f"相机 {camera_id} (720x1280)"
    cv2.namedWindow(window_name_small, cv2.WINDOW_NORMAL)
    cv2.namedWindow(window_name_large, cv2.WINDOW_NORMAL)
    
    try:
        while True:
            # 读取一帧图像
            ret, frame = cap.read()
            
            # 检查是否成功获取图像
            if not ret:
                print("警告：无法获取图像帧")
                break
            
            # 调整图像大小
            resized_small = cv2.resize(frame, (640, 480))  # 480x640
            
            # 显示两个分辨率的图像
            cv2.imshow(window_name_small, resized_small)
            cv2.imshow(window_name_large, frame)
            
            # 按ESC键退出
            key = cv2.waitKey(1) & 0xFF
            if key == 27:  # ESC键的ASCII码
                break
    
    finally:
        # 释放资源
        cap.release()
        cv2.destroyAllWindows()
        print("相机已关闭")

def main():
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description='打开相机并显示图像')
    parser.add_argument('-i', '--id', type=int, default=0,
                        help='相机ID (默认: 0)')
    
    # 解析命令行参数
    args = parser.parse_args()
    
    # 打开相机
    open_camera(args.id)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n程序被用户中断")
        sys.exit(0)
